from django.http import JsonResponse
from django.views import generic
from django.shortcuts import render,redirect,HttpResponse,get_list_or_404

from firstplan import models
from firstplan.mine import myform
from firstplan.mine.pagination import Pagination
from firstplan.models import EverydayResult


def everyday_list(request):
    """每日完成情况列表"""
    title = '每日完成情况'
    form = myform.EverydayList()
    # data_dict = {}
    # search_data = request.GET.get('page', '')
    # if search_data:
    #     data_dict['date__contains'] = search_data
    # queryset = models.EverydayResult.objects.filter(**data_dict)
    queryset = models.EverydayResult.objects.all().order_by("-date","-id")
    # 实例化分页对象
    page_obj = Pagination(request, queryset, page_param="page", page_size=9, plus=5)
    # 分页后返回的数据
    context = {
        "queryset": page_obj.queryset,  # 分完页后的数据
        "page_string": page_obj.html(),  # 生成页码
        'form': form,
        'title': title
    }
    return render(request,'everyday.html',context)


def everyday_add(request):
    """每日完成情况添加"""
    title = '每日完成情况--添加'
    if request.method == 'GET':
        form = myform.EverydayList()
        return render(request,'add_or_edit.html',{'form':form,'title':title})

    form = myform.EverydayList(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        if not models.EverydayResult.objects.filter(date=form.cleaned_data['date'],person=form.cleaned_data['person'],event=form.cleaned_data['event']).exists():
            form.save()
            return redirect('/everyday/list/')
        print("数据已重复")
    return render(request, 'add_or_edit.html', {'form': form, 'title': title})


def everyday_edit(request,uid):
    """每日完成情况修改"""
    title = '每日完成情况--修改'
    everyday_obj = models.EverydayResult.objects.filter(id=uid).first()
    # everyday_obj = get_list_or_404(EverydayResult,pk=uid)[0]  # 若数据库中没有，报错：Not Found:。。404 3009。【It raises Http404 if the list is empty】

    if request.method == 'GET':
        form = myform.EverydayList(instance=everyday_obj)
        return render(request, 'add_or_edit.html', {'form': form,'title': title})

    form = myform.EverydayList(data=request.POST,instance=everyday_obj)
    if form.is_valid():
        form.save()
        return redirect('/everyday/list/')

    return render(request, 'add_or_edit.html', {'form': form, 'title': title})


def everyday_delete(request,uid):
    """每日完成情况删除"""
    title = '每日完成情况--删除'

    everyday_obj = models.EverydayResult.objects.filter(id=uid)
    if everyday_obj:
        everyday_obj.delete()
    return redirect('/everyday/list/')


def everyday_add2(request):
    """每日完成情况添加2"""
    title = '每日完成情况--添加(多项添加)'
    queryset = models.PlanEvent.objects.all()
    queryset1 = models.Person.objects.all()
    if request.method == 'GET':
        return render(request, 'add2.html', {'queryset1': queryset1, 'queryset': queryset, 'title': title})
    # events = [query["event"] for query in queryset]
    # print("events: ",events)
    date = request.POST.get("date")
    person = request.POST.get("person")
    event_list = request.POST.getlist("event")
    print(request.POST)

    for event in event_list:
        if not models.EverydayResult.objects.filter(date=date,person_id=person,event_id=event).exists():
            models.EverydayResult.objects.create(date=date,person_id=person,event_id=event)
    return redirect('/everyday/list/')